<!DOCTYPE html>
<html lang="zh-CN"
      xmlns="http://www.w3.org/1999/xhtml"
      xmlns:th="http://www.thymeleaf.org"
      xmlns:layout="http://www.ultraq.net.nz/thymeleaf/layout"
      layout:decorator="model/boardModel">
<head>
  <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"/>

  <title>物品列表</title>
  <style type="text/css">
    .modal-dialog {
      position: absolute;
      top: 0;
      bottom: 0;
      left: 0;
      right: 0;
    }
/*
    .modal-content {
      !*overflow-y: scroll; *!
      position: absolute;
      top: 0;
      bottom: 0;
      width: 100%;
    }

    .modal-body {
      overflow-y: scroll;
      position: absolute;
      top: 55px;
      bottom: 65px;
      width: 100%;
    }

    .modal-footer {
      position: absolute;
      width: 100%;
      bottom: 0;
    }*/
  </style>
</head>
<body>

  <div th:fragment="pagenav" th:remove="tag">
    <div th:replace="model/nav :: pageheader ('评估产品','产品管理')"></div>
  </div>

  <div th:fragment="content" th:remove="tag">




    <div class="row" >
      <div class="col-xs-12">

        <div class="box box-primary">
          <div class="box-header with-border">
            <h3 class="box-title">查询条件</h3>
            <div class="box-tools pull-right">
              <button class="btn btn-box-tool" data-widget="collapse"><i class="fa fa-minus"></i></button>
            </div>
          </div>
          <!-- /.box-header -->
          <!-- form start -->
          <form id="queryForm" th:action="@{/esti/list}" method="post" >
            <div class="box-body">
              <div class="row">

                <div class="col-xs-3">
                  <input type="text" th:name="productName" class="form-control input-sm" placeholder="名称"/>
                </div>
                <div class="col-xs-3">
                  <input type="text" th:name="model" class="form-control input-sm" placeholder="型号"/>
                </div>
                <div class="col-xs-3">
                  <select id="brandId" th:name="brandId" class="form-control input-sm" placeholder="品牌">
                    <option value="">所有品牌</option>
                    </select>
                </div>

                <div class="col-xs-3">
                  <button id="btn-query" type="button" class="btn btn-primary pull-right btn-sm">查询</button>
                </div>
              </div>
            </div>
            <!-- /.box-body -->

            <div class="box-footer">

            </div>
          </form>
        </div>


        <div class="box">
          <!--<div class="box-header">
            <h3 class="box-title">用户列表</h3>

            <div class="box-tools">
              <a href="/user/add"><button type="button" class="btn btn-primary btn-sm" onclick="">新增</button></a>
            </div>

          </div>-->
          <div class="box-body">
            <table id="dataTable" class="table table-striped table-bordered table-hover table-condensed">

              <thead >
              <tr>
                <th>选择</th>
                <th>产品名称</th>
                <th>品牌</th>
                <th>型号</th>
                <th>最低价格</th>
                <th>最高价格</th>
                <th>当前状态</th>
                <th>操作</th>
              </tr>
              </thead>


            </table>

           <!-- <div th:include="model/page :: pager" th:remove="tag"></div>-->

          </div>
          <!-- /.box-body -->
        </div>
        <!-- /.box -->
      </div>

    </div>



    <!-- EditUser -->
    <div class="modal fade" id="editModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
      <div class="modal-dialog">
        <div class="modal-content">

          <div class="modal-header" style="background-color: #307095;">
            <button type="button" class="close" data-dismiss="modal">
              <span aria-hidden="true">&times;</span><span class="sr-only">关闭</span>
            </button>
            <h4 class="modal-title" id="myModalLabel2">信息-编辑</h4>
          </div>

          <div class="modal-body">
            <form class="form-horizontal"  id="editForm" action="/esti/edit" method="post">
              <input type="hidden" class="form-control" name="productId"/>
              <div class="form-group">
                <label  class="col-sm-3 control-label">物品名称</label>
                <div class="col-sm-9">
                  <input type="text" class="form-control" name="productName"/>
                </div>
              </div>
              <div class="form-group">
                <label class="col-sm-3 control-label">品牌</label>
                <div class="col-sm-9">
                  <select id="edit-brand" name="brandId" class="form-control" placeholder="品牌">
                  </select>
                </div>
              </div>
              <div class="form-group">
                <label class="col-sm-3 control-label">型号</label>
                <div class="col-sm-9">
                  <input type="text" class="form-control" name="model"/>
                </div>
              </div>
              <div class="form-group">
                <label class="col-sm-3 control-label">图片</label>
                <div class="col-sm-9">
                  <img id="showImage" th:src="@{/dist/img/pictures.png}" style="float:left;" width="80" height="110" />
                </div>
                <div class="col-sm-9">
                  <input type="hidden" name="imageUrl" id="imageUrl" value=""/>
                  <a id="selectImage" class="btn btn-primary" style="height: 21px;font-size: 12px;text-align: center;padding-top: 2px;position:absolute;left: 166px;top:-10px;" href="javascript:;">点击上传</a>
                </div>
              </div>
              <div class="form-group">
                <label class="col-sm-3 control-label">分类</label>
                <div class="col-sm-9">
                  <select name="categoryId" class="form-control">
                    <option value="1" >手机</option>
                    <option value="8" >平板</option>
                  </select>
                </div>
              </div>
              <div class="form-group">
                <label class="col-sm-3 control-label">最高价</label>
                <div class="col-sm-9">
                  <input type="text" class="form-control" name="price" data-rule-required="true" data-msg-required="请录入最高价"
                         data-rule-commonString ="true"/>
                </div>
              </div>
              <div class="form-group">
                <label class="col-sm-3 control-label">最低价</label>
                <div class="col-sm-9">
                  <input type="text" class="form-control" name="lowPrice" data-rule-required="true" data-msg-required="请录入最低价"
                         data-rule-commonString ="true"/>
                </div>
              </div>
              <div class="form-group">
                <label class="col-sm-3 control-label">状态</label>
                <div class="col-sm-9">
                  <select id="edit-status" name="status" class="form-control" placeholder="">
                    <option value="1">正常</option>
                    <option value="0">未审核</option>
                  </select>
                </div>
              </div>

              <div class="form-group">
                <span><code>注：型号是判定手机检测的唯一标识，因手机系统商家标准不一。
                  苹果手机此处应填写其平台标号 如：AppleTV5,3/Watch2,4/iPad6,4/iPhone9,4 等。
                  具体手机型号 如：A1661，A1785，A1786等同一平台产品，请在评估细项中添加。
                安卓手机此处 如果一款手机只有单个手机型号可在此处配置，有多个手机型号则请在评估细项中添加。</code></span>
              </div>

            </form>
          </div>
          <!-- modal-body END -->

          <div class="modal-footer">
            <button type="submit" id="btn-submit" class="btn btn-primary">提交</button>
          </div>
        </div>
      </div>
    </div>

    <!--Adjust-->
    <div class="modal fade" id="adjustModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
      <div class="modal-dialog">
        <div class="modal-content">

          <div class="modal-header" style="background-color: #307095;">
            <button type="button" class="close" data-dismiss="modal">
              <span aria-hidden="true">&times;</span><span class="sr-only">关闭</span>
            </button>
            <h4 class="modal-title" id="myModalLabel3">价格调整</h4>
          </div>

          <div class="modal-body">
            <form class="form-horizontal"  id="adjustForm" action="/esti/edit" method="post">
              <div class="form-group">
                <label  class="col-sm-3 control-label">最高价比例</label>
                <div class="col-sm-9">
                  <input type="text" class="form-control" name="highAdjust" onchange="checknum(value)"/>
                </div>
              </div>
              <div class="form-group">
                <label  class="col-sm-3 control-label">最低价比例</label>
                <div class="col-sm-9">
                  <input type="text" class="form-control" name="lowAdjust" onchange="checknum(value)"/>
                </div>
              </div>
              <div class="form-group">
                <label  class="col-sm-3 control-label">评估项比例</label>
                <div class="col-sm-9">
                  <input type="text" class="form-control" name="itemAdjust" onchange="checknum(value)"/>
                </div>
              </div>

              <div class="form-group">
                <span><code>注：比例填写时请填写降低的百分比，如：降低15%，则填写15 。</code></span>
              </div>

            </form>
          </div>
          <!-- modal-body END -->

          <div class="modal-footer">
            <button type="submit" id="btn-adjustsubmit" class="btn btn-primary">确定</button>
          </div>
        </div>
      </div>
    </div>



    <script th:src="@{/plugins/jQuery/plupload.full.min.js}"></script>
    <script>

      $(function (){

        var brands;
        //加载品牌列表
        $.getJSON("/brand/all",function(result){
          brands = result;
          $.each(result, function(i, item){
            $("#brandId").append("<option value="+item.brandId+">"+item.brandName+"</option>");
          });
        });

        var tables = $("#dataTable").dataTable({
          serverSide: true,//分页，取数据等等的都放到服务端去
          processing: true,//载入数据的时候是否显示“载入中”
          pageLength: 10,  //首次加载的数据条数
          ordering: false,//排序操作在服务端进行，所以可以关了。
          pagingType: "full_numbers",
          autoWidth: false,
          stateSave: true,//保持翻页状态，和tables.fnDraw(false);结合使用
          searching: false,
          ajax: {   //类似jquery的ajax参数，基本都可以用。
            type: "post",//后台指定了方式，默认get，外加datatable默认构造的参数很长，有可能超过get的最大长度。
            url: "/esti/list",
            dataSrc: "data",//默认data，也可以写其他的，格式化table的时候取里面的数据
            data: function (d) {//d是原始的发送给服务器的数据，默认很长。
              var param = {}; //因为服务端排序，可以新建一个参数对象
              param.draw = d.draw;
              param.start = d.start;
              param.length = d.length;
              var formData = $("#queryForm").serializeArray();//把form里面的数据序列化成数组
              formData.forEach(function (e) {
                param[e.name] = e.value;
              });
              return param;//自定义需要传递的参数。
            }
          },
          columns: [
              //对应上面thead里面的序列
            {"data": null, "width": "50px"},
            {"data": 'productName'}, //mData 表示发请求时候本列的列明，返回的数据中相同下标名字的数据会填充到这一列
            {"data": 'brandName', defaultContent: ""},
            {"data": 'model', defaultContent: ""},
            {"data": 'lowPrice', defaultContent: ""},
            {"data": 'price', defaultContent: ""},
            {"data": 'status',
             "render":function(data,type,full,callback) {
             switch(data){
             case 1: return '正常';break;
             case 0: return '未审核';break;
             default:return '未审核';
             }
             }
             },
            {"data": null,"width":"200px"}
          ],

          /*<![CDATA[*/
          columnDefs: [
            {
              targets: -1,//编辑
              data: null,//下面这行，添加了编辑按钮和，删除按钮
              defaultContent: "<div class='btn-group'><button id='editRow' class='btn btn-primary btn-sm' type='button'>编辑<i class='fa fa-edit'></i></button>" +
              "<button id='proRow' class='btn btn-primary btn-sm' type='button'>评估<i class='fa fa-cog'></i></button>" +
              "<button id='delRow' class='btn btn-primary btn-sm' type='button'>删除<i class='fa fa-trash-o'></i></button></div>"
            },
            {
                  'targets': 0,
                  'searchable':false,
                  'orderable':false,
                  'className': 'dt-body-center1',
                  'render': function (data, type, full, meta){
                      return '<input type="checkbox" name="id[]" value="'
                          + data.productId + '" >';
                  }
            }
          ],
          dom: '<"toolbar">frtip',
          /*]]>*/

          //每加载完一行的回调函数
          createdRow: function( row, data, index ) {
            //修改单元格样式
            //$('td', row).eq(5).css('font-weight',"bold").css("color","red");//获取到具体行具体格的元素
          },
          initComplete: function (setting, json) {
            //初始化完成之后替换原先的搜索框。
          },



          language: {
            lengthMenu: "",//不显示记录条数选择
            //lengthMenu: '<select class="form-control input-xsmall">' + '<option value="5">5</option>' + '<option value="10">10</option>' + '<option value="20">20</option>' + '<option value="30">30</option>' + '<option value="40">40</option>' + '<option value="50">50</option>' + '</select>条记录',//左上角的分页大小显示。
            processing: "加载中",//处理页面数据的时候的显示
            /*<![CDATA[*/
            paginate: {//分页的样式文本内容。
              previous: "<",
              next: ">",
              first: "<<",
              last: ">>"
            },
            /*]]>*/
            zeroRecords: "没有数据",//table tbody内容为空时，tbody的内容。
            //下面三者构成了总体的左下角的内容。
            //info: "共 _PAGES_ 页，显示第 _START_ 到第 _END_ 条 ",//筛选之后得到 _TOTAL_ 条，初始 _MAX_ 条   左下角的信息显示，大写的词为关键字。
            info: "共 _PAGES_ 页，显示第 _START_ 到第 _END_ 条",
            infoEmpty: "0条记录",//筛选为空时左下角的显示。0条记录
            infoFiltered: "",//筛选之后的左下角筛选提示(另一个是分页信息显示，在上面的info中已经设置，所以可以不显示)，
            sSearch: "关键字："
          }

        });

        /*<![CDATA[*/
        $("div.toolbar").html('<button type="button" class="btn btn-primary btn-sm" id="btn-add">新增</button>&nbsp<button type="button" class="btn btn-primary btn-sm" id="btn-adjust">系数调整</button>');

        /*]]>*/

          //调整价格按钮
          $("#btn-adjust").on("click", function () {
              //show 之前清空
              $("#adjustModal").modal("show");
          });

          //调整价格按钮

          $("#btn-adjustsubmit").on("click", function () {
          //highAdjust lowAdjust  itemAdjust
              var id_array=new Array();
              $('input[name="id[]"]:checked').each(function(){
                  id_array.push($(this).val());//向数组中添加元素
              });
              var idstr=id_array.join('a');//将数组元素连接起来以构建一个字符串
              var data = $("#adjustForm").serialize()
              var highAdjust = $("#adjustForm input[name=highAdjust]").val()
              var lowAdjust = $("#adjustForm input[name=lowAdjust]").val()
              var itemAdjust = $("#adjustForm input[name=itemAdjust]").val()
              /*<![CDATA[*/
              data = data + '&ids='+idstr;
              /*]]>*/


              if(idstr == "" || isNaN(highAdjust) || isNaN(lowAdjust) || isNaN(itemAdjust)){
                  toastr.error("请选择数据并填写比例系数");
              }else {
                      $.ajax({
                          type: "POST",
                          url: "/esti/adjust",
                          data: data,
                          dataType: "json",
                          success: function(result){
                              if (result.result == 200) {
                                  $('#dataTable').DataTable().ajax.reload();
                                  toastr.success(result.msg);
                                  $("#adjustModal").modal("hide");

                              } else {
                                  toastr.error(result.msg);
                              }
                          },
                          error:function () {
                              toastr.error("网络错误...");
                          }
                      });

              }

          });


        //查询按钮
        $("#btn-query").on("click", function () {
           tables.fnDraw();
        });
        var url="/esti/add";
        //添加
        $("#btn-add").on("click", function () {
          url = "/esti/add";

          $.each(brands, function(i, item){
            $("#edit-brand").append("<option value="+item.brandId+">"+item.brandName+"</option>");
          });

          $("#editModal input[name=productId]").val(0);
          $("#editModal input[name=productName]").val("");
          $("#editModal input[name=model]").val("");
            $("#imageUrl").val("");
            $("#showImage").attr("src","/dist/img/pictures.png");
          $("#edit-brand").val(null);
          $("#editModal input[name=categoryId]").val(null);
          $("#editModal input[name=price]").val(null);
          $("#editModal input[name=lowPrice]").val(null);

          $("#editModal").modal("show");

        });

        //修改
        $("#dataTable tbody").on("click", "#editRow", function () {
          var data = tables.api().row($(this).parents("tr")).data();

          $.each(brands, function(i, item){
            $("#edit-brand").append("<option value="+item.brandId+">"+item.brandName+"</option>");
          });

          $("#editModal input[name=productId]").val(data.productId);
          $("#editModal input[name=productName]").val(data.productName);
          $("#editModal input[name=model]").val(data.model);
          $("#imageUrl").val(data.imageUrl);
          $("#showImage").attr("src",data.imageUrl);
          $("#edit-brand").val(data.brandId);
          $("#editModal input[name=categoryId]").val(data.categoryId);
          $("#editModal input[name=price]").val(data.price);
          $("#editModal input[name=lowPrice]").val(data.lowPrice);
          var status=""+data.status;
          $("#edit-status").val(status);

          url = "/esti/edit";

          $("#editModal").modal("show");
        });

        //添加、修改  表单异步提交
        $("#btn-submit").on("click", function(){
          $.ajax({
            cache: false,
            type: "POST",
            url: url,
            data: $("#editForm").serialize(),
            dataType: "json",
            async: false,
            error: function(request) {
              toastr.error("网络错误...");
            },
            success: function(data) {
           //   data = $.parseJSON(data);
              if(data.result == "200"){
                $("#editModal").modal("hide");
                tables.fnDraw();
                toastr.success(data.msg);
              }else{
                toastr.error(data.msg);
              }
            }
          });
        });


        //删除
        $("#dataTable tbody").on("click", "#delRow", function () {
          var data = tables.api().row($(this).parents("tr")).data();
          bootbox.confirm(
                  {
                    message: "确认要删除吗",
                    buttons: {
                      confirm: {
                        label: '确认'
                      },
                      cancel: {
                        label: '取消'
                      }
                    },
                    callback: function (result) {
                      // 返回 true  或者false
                      if (result) {
                        $.ajax({
                          url:'/esti/'+data.productId,
                          type:'POST',
                          dataType: "json",
                          cache: "false",
                          success:function(result){
                            if(result.result == 200){
                              toastr.success(result.msg);
                              tables.api().row().remove().draw(false);
                            }else{
                              toastr.error(result.msg);
                            }
                          },
                          error:function(err){
                            toastr.error("网络错误...");
                          }
                        });
                      }
                    }
                  });


        });


        $("#dataTable tbody").on("click", "#proRow", function () {
          var data = tables.api().row($(this).parents("tr")).data();
          location.href="/esti/"+data.productId;
        });


      })

      var uploader = new plupload.Uploader({
          runtimes : 'html5,flash,silverlight',//设置运行环境，会按设置的顺序，
          url : '/sysUpload/uploadImg',
          max_file_size : '10M',
          browse_button : 'selectImage',
          filters : [ {
              title : 'Image files',
              extensions : 'jpg,gif,png'
          }],
          init : {
              FilesAdded: function(up, files) {
                  uploader.start();
                  return false;
              },
              FileUploaded : function(up, file, info) {//文件上传完毕触发
                  console.log("单独文件上传完毕");
                  var response = $.parseJSON(info.response);
                  if(response.result==200){
                      alert(response.msg);
                      $("#imageUrl").val(response.data);
                      $("#showImage").attr("src",response.data);
                  }else{
                      alert(response.msg);
                  }
              }
          }
      });
      uploader.init();

      function checknum(value) {
          if (isNaN(value)) {
              alert("请输入数字");
              return false
          }
          return true
      }

    </script>


  </div>


</body>
</html>
